// releasePage/pages/addBusinessHall/addBusinessHall.js
import throttle from '../../../utils/throttle.js';
import Http from '../../../utils/http.js';
const http = new Http();
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        review: '', //审核编辑标记位
        id: '',
        businessHallValue: '', //营业厅运营商名称
        businessHallId: '', //营业厅运营商ID
        nameValue: '',
        phoneValue: '',
        sceneImageArr: [], //上传照片
        description: '',
        // 定位
        lng: '',
        lat: '',
        city: '',
        country: '',
        gps: '',
        address: '',
        //按钮active
        btnActive: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (app.globalData.isIpx) {
            this.setData({
                ipxBottom: 34,
            });
        }
        if (options.id) {
            wx.setNavigationBarTitle({
                title: '编辑营业厅',
            });
            this.getBusinesshallDetails(options.id);
        } else {
            wx.setNavigationBarTitle({
                title: '添加营业厅',
            });
        }
        this.setData({
            id: options.id,
            review: options.review || '',
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    // 选择运营商
    operatorType(e) {
        wx.navigateTo({
            url: `./operatorList/operatorList?businessHall=${this.data.businessHallValue}`,
        });
    },
    name(e) {
        this.setData({
            nameValue: e.detail.value,
        });
    },
    phone(e) {
        this.setData({
            phoneValue: e.detail.value,
        });
    },
    description(e) {
        this.setData({
            description: e.detail.value,
        });
        app.numLimitTip(e.detail.value.length, 500);
    },
    // GPS选择
    openLocation: function (e) {
        var _this = this;
        wx.chooseLocation({
            latitude: app.globalData.cityLat,
            longitude: app.globalData.cityLng,
            success: function (res) {
                _this.setData({
                    address: res.address || res.name,
                    lng: res.longitude,
                    lat: res.latitude,
                    gps:
                        res.longitude.toFixed(1) +
                        '°E，' +
                        res.latitude.toFixed(1) +
                        '°N',
                });
            },
            fail: function (res) {
                console.log(res);
            },
        });
    },
    addressTap(e) {
        wx.navigateTo({
            url: `../homePageInfo/address/address?address=${this.data.address}`,
        });
    },
    // 添加图片
    addImg(e) {
        const that = this;
        wx.chooseImage({
            count: 8 - that.data.sceneImageArr.length,
            success(res) {
                let imgLen =
                    that.data.sceneImageArr.length + res.tempFilePaths.length;
                if (imgLen > 8) {
                    wx.showModal({
                        content: '最多上传8张图片，请重新上传',
                        showCancel: false,
                    });
                    return;
                } else {
                    wx.showLoading({
                        title: '图片上传中',
                        mask: true,
                    });
                    const imgUploadResults = [];
                    let index = that.data.sceneImageArr.length;
                    for (let i = 0; i < res.tempFilePaths.length; i++) {
                        let imgUploadResult = app
                            .imgUpload(res.tempFilePaths[i])
                            .then((res) => {
                                let num = i + index;
                                that.data.sceneImageArr[num] = res;
                                that.setData({
                                    sceneImageArr: that.data.sceneImageArr,
                                });
                                console.log(that.data.sceneImageArr);
                            });
                        imgUploadResults.push(imgUploadResult);
                    }
                    Promise.all(imgUploadResults).then((values) => {
                        wx.hideLoading();
                    });
                }
            },
        });
    },
    // 删除图片
    deleteImg(e) {
        let index = e.currentTarget.dataset.index;
        console.log(index);
        this.data.sceneImageArr.splice(index, 1);
        this.setData({
            sceneImageArr: this.data.sceneImageArr,
        });
    },
    // 预览图片
    previewImage(e) {
        const current = e.target.dataset.src;
        wx.previewImage({
            current,
            urls: this.data.sceneImageArr,
        });
    },
    // 提交
    submit: throttle(
        function (e) {
            let _that = this;
            if (app.visitorPublish()) return; //游客发布限制
            if (
                !_that.data.businessHallId ||
                !_that.data.address ||
                !_that.data.sceneImageArr.length
            )
                return;
            if (!_that.data.id) {
                wx.request({
                    url:
                        app.globalData.rootPath +
                        `cjMap/createBusinesshall?authId=${app.globalData.authId}`,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json',
                    },
                    data: {
                        delflg: '02', //删除标志 00未删除 01已删除 02待审核10草稿
                        address: _that.data.address,
                        lng: _that.data.lng,
                        lat: _that.data.lat,
                        picurl: JSON.stringify(_that.data.sceneImageArr),
                        operatorid: _that.data.businessHallId,
                        effectiveflg: '00',
                        backup: _that.data.description,
                        contactor: _that.data.nameValue,
                        phone: _that.data.phoneValue,
                        city: app.globalData.addressBack, //城市
                        country: app.globalData.countryBack, //国家
                    },
                    success: function (res) {
                        console.log(res);
                        wx.showToast({
                            title: '录入成功',
                            icon: 'success',
                            duration: 2000,
                        });
                        let pages = getCurrentPages(); //当前页面栈
                        let prevPage = pages[pages.length - 2]; //上一页面
                        let prevPage1 = pages[pages.length - 3];
                        if (prevPage && typeof prevPage.refresh == 'function') {
                            prevPage.refresh(['businesshall', 'count']);
                        }
                        if (
                            prevPage1 &&
                            typeof prevPage1.refresh == 'function'
                        ) {
                            prevPage1.refresh(['businesshall', 'count']);
                        }
                    },
                });
            } else {
                //编辑问题
                wx.request({
                    url:
                        app.globalData.rootPath +
                        `cjMap/editBusinesshall?authId=${app.globalData.authId}`,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json',
                    },
                    data: {
                        delflg: '02', //删除标志 00未删除 01已删除 02待审核10草稿
                        address: _that.data.address,
                        lng: _that.data.lng,
                        lat: _that.data.lat,
                        picurl: JSON.stringify(_that.data.sceneImageArr),
                        operatorid: _that.data.businessHallId,
                        effectiveflg: '00',
                        backup: _that.data.description,
                        contactor: _that.data.nameValue,
                        phone: _that.data.phoneValue,
                        city: _that.data.city || app.globalData.addressBack, //城市
                        country:
                            _that.data.country || app.globalData.countryBack, //国家
                        id: _that.data.id,
                    },
                    success: function (res) {
                        if (!_that.data.review) {
                            wx.showToast({
                                title: '录入成功',
                                icon: 'success',
                                duration: 2000,
                            });
                            app.globalData.indexExpRefresh = true;
                            wx.removeStorageSync('refreshMapPointId');
                            let pages = getCurrentPages(); //当前页面栈
                            let prevPage = pages[pages.length - 2]; //上一页面
                            let prevPage1 = pages[pages.length - 3];
                            if (
                                prevPage &&
                                typeof prevPage.getBusinesshallDetails ==
                                    'function'
                            ) {
                                prevPage.setData(
                                    {
                                        //本页面数据赋值到上一个页面
                                        id: res.data.data.id,
                                    },
                                    () => {
                                        prevPage.getBusinesshallDetails();
                                    }
                                );
                            }
                            if (
                                prevPage1 &&
                                typeof prevPage1.refresh == 'function'
                            ) {
                                prevPage1.refresh(['businesshall', 'count']);
                            }
                        } else {
                            console.log(res);
                            app.doVerify(res.data.data.id, '15');
                        }
                    },
                });
            }
            if (!_that.data.review) {
                setTimeout(function () {
                    wx.navigateBack({
                        delta: 1, // 返回上一级页面。
                    });
                }, 2000);
            }
        },
        4000,
        {
            trailing: false,
        }
    ),
    //获取详情
    getBusinesshallDetails(id) {
        let _that = this;
        http.getRequest(
            `cjMap/getBusinesshallDetails?authId=${app.globalData.authId}&id=${id}`
        ).then((res) => {
            if (res.status == 0) {
                console.log(res);
                _that.setData({
                    businessHallValue: res.data.operator, //营业厅运营商名称
                    businessHallId: res.data.operatorid, //营业厅运营商ID
                    nameValue: res.data.contactor,
                    phoneValue: res.data.phone,
                    description: res.data.backup,
                    // 定位
                    lng: res.data.lng,
                    lat: res.data.lat,
                    city: res.data.city,
                    country: res.data.country,
                    gps:
                        res.data.lng.toFixed(1) +
                        '°E，' +
                        res.data.lat.toFixed(1) +
                        '°N',
                    address: res.data.address,
                    sceneImageArr: res.data.picurl
                        ? JSON.parse(res.data.picurl)
                        : [],
                });
            }
        });
    },
});
